package com.lintf.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lintf.common.exception.ServiceException;
import com.lintf.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author lin tingfeng
 * @system Mac
 * @data 2024/7/30 13:59
 * @package_name com.lintf.framework
 * @project_name mobile-project
 * @desc
 */
@Slf4j
@Component
public class CommonFieldHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = SecurityUtils.getUserId();
        if (userId != null) {
            String fieldVal = String.valueOf(userId);
            this.strictInsertFill(metaObject, "createBy", String.class, fieldVal);
            this.strictInsertFill(metaObject,"createTime", Date.class,new Date());
            this.strictInsertFill(metaObject, "updateBy", String.class, fieldVal);
            this.strictInsertFill(metaObject,"updateTime", Date.class,new Date());
        } else {
            throw new ServiceException("新增时获取用户信息异常");
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = SecurityUtils.getUserId();
        if (userId != null) {
            String fieldVal = String.valueOf(userId);
            this.strictUpdateFill(metaObject, "updateBy", String.class, fieldVal);
            this.strictInsertFill(metaObject,"updateTime", Date.class,new Date());
        } else {
            throw new ServiceException("更新时获取用户信息异常");
        }
    }
}
